#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "os.h"
#include "filterapi.h"
#include "filter.h"


#define FILTER_DEBUG(fmt, ...) //SM_Printf(fmt, ##__VA_ARGS__)
unsigned int Filter_Task(void* pParam)
{
	static unsigned char au8Buffer[512*1024+188];
	unsigned int u32ReadPos = 0;
	unsigned int u32WritedPos = 0;
	unsigned char u8Sync = 0;
	unsigned int u32BytesDroped;//for debug

	FILTER_DEBUG("Filter_Task entry\r\n");
	//SM_OsSetPriority(100);
	
	while(1)
	{
		u32WritedPos += Filter_ReadTS(au8Buffer+u32WritedPos, sizeof(au8Buffer)-u32WritedPos);
		if(u32WritedPos>0x40000)
		{
			SM_Printf("Filter_Task Filter_ReadTS return > 128K, u32WritedPos = 0x%x, tick = %d\r\n", u32WritedPos, SM_OsTickCountGet());
		}
		while(u32ReadPos+188 < u32WritedPos)
		{
			if(u8Sync==1 && au8Buffer[u32ReadPos] == 0x47)//sync, start with 0x47
			{
				FILTER_DEBUG("Filter_Task Filter_Process\r\n");
				Filter_Process(&au8Buffer[u32ReadPos]);
				u32ReadPos += 188;
			}
			else if(u8Sync==1 && au8Buffer[u32ReadPos] != 0x47)//sync, start with not 0x47
			{
				FILTER_DEBUG("Filter_Task not sync\r\n");
				u32ReadPos++;
				u8Sync = 0;
				u32BytesDroped = 1;//for debug
				continue;
			}
			else if(au8Buffer[u32ReadPos] == 0x47)//not sync, start with 0x47
			{
				if(au8Buffer[u32ReadPos+188]==0x47)
				{
					FILTER_DEBUG("Filter_Task sync\r\n");
					//SM_Printf("Filter_Task sync after drop %d Bytes\r\n", u32BytesDroped);
					u8Sync = 1;
					Filter_Process(&au8Buffer[u32ReadPos]);
					u32ReadPos += 188;
				}
				else //continue read
				{
					u32ReadPos++;
					u32BytesDroped++;//for debug
				}
			}
			else//not sync, au8Buffer[u32ReadPos] != 0x47
			{
				u32ReadPos++;
				u32BytesDroped++;//for debug
			}
		}
		if(u32WritedPos-u32ReadPos<=188)
		{
			memcpy(au8Buffer, au8Buffer+u32ReadPos, u32WritedPos-u32ReadPos);
			u32WritedPos = u32WritedPos-u32ReadPos;
			u32ReadPos = 0;
		}
	}
	return 0;
}

int Filter_Start()
{
	unsigned int hThreadId;
	
	SM_OsThreadCreate(0, Filter_Task, NULL, &hThreadId);
	//SM_OsThreadCreateEx(0, Filter_Task, NULL, &hThreadId, 100);
	
	return 0;
}
